package cn.itcast.controller;

import cn.itcast.pojo.PageBean;
import cn.itcast.pojo.Result;
import cn.itcast.pojo.Students;
import cn.itcast.service.StudentsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

@RestController
@RequestMapping("/students")
@Slf4j
public class StudentsController {
    @Autowired
    private StudentsService studentsService;
    @GetMapping
    public Result findAllColStudents(
            String name,
            Integer degree,
            Integer classId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize
    ){
        PageBean<Students> students = studentsService.findAllColStudents(name, degree, classId, page, pageSize);
        log.warn("查询结果：{}",students);
        return students == null || students.getRows().size() == 0 ? Result.error("没有查询到数据") : Result.success( "查询成功",students);
    }


    //如果前端传过来的是数组,我们可以直接用数组接收,用集合接收需要添加@PathVariable
    //批量删除学生
    @DeleteMapping("/{ids}")
    public Result deleteById(@PathVariable ArrayList<Integer> ids){
        boolean result = studentsService.deleteById(ids);
        return result ? Result.success("删除成功") : Result.error("删除失败");
    }
    @PostMapping
    public Result addStudents(@RequestBody Students students){
        boolean result = studentsService.addStudents(students);
        return result ? Result.success("添加成功") : Result.error("添加失败");
    }
    @GetMapping("/{id}")
    public Result findStudentsById(@PathVariable Integer id){
        Students students = studentsService.findStudentsById(id);
        return students == null ? Result.error("没有查询到数据") : Result.success("查询成功",students);
    }

    @PutMapping
    public Result updateStudents(@RequestBody Students students){
        boolean result = studentsService.updateStudents(students);
        return result ? Result.success("修改成功") : Result.error("修改失败");
    }

    @PutMapping("/violation/{id}/{score}")
    public Result discipline(@PathVariable Integer id, @PathVariable Integer score){
        boolean result = studentsService.discipline(id, score);
        return result ? Result.success("修改成功") : Result.error("修改失败");
    }


    private static final String TEMP_DIR = System.getProperty("java.io.tmpdir");
    public StudentsController(StudentsService studentService) {
        this.studentsService = studentService;
    }

    @PostMapping("/import")
    public String importExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "请选择文件";
        }
        try {
            // 创建唯一文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID() + suffix;
            // 创建临时文件
            File tempFile = new File(TEMP_DIR + fileName);
            file.transferTo(tempFile);
            // 执行导入
            studentsService.importStudents(tempFile.getAbsolutePath());
            // 删除临时文件
            if (tempFile.exists()) {
                tempFile.delete();
            }

            return "导入成功";
        } catch (IOException e) {
            return "导入失败: " + e.getMessage();
        } catch (Exception e) {
            return "系统错误: " + e.getMessage();
        }
    }
    /**
     * 导出Excel
     */
    @GetMapping("/export")
    public void exportExcel() {
        // 执行导出
        studentsService.exportStudents();
    }
}
